package com.cskaoyan.market.admin.controller;

import com.cskaoyan.market.admin.service.MarketLogService;
import com.cskaoyan.market.admin.service.impl.MarketLogServiceImpl;
import com.cskaoyan.market.db.domain.MarketLog;
import com.cskaoyan.market.util.JacksonUtil;
import com.cskaoyan.market.util.ResponseUtil;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/admin/log/*")
public class AdminLogController extends HttpServlet {

    private MarketLogService logService = new MarketLogServiceImpl();

    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    }

    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String requestURI = req.getRequestURI();
        String op = requestURI.replace(req.getContextPath() + "/admin/log/", "");
        if ("list".equals(op)) {
            list(req, resp);
        }
    }

    /**
     * 系统操作日志类的方法分发
     *
     * @param req
     * @param resp
     */
    private void list(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String page = req.getParameter("page");
        String limit = req.getParameter("limit");
        String sort = req.getParameter("sort");
        String order = req.getParameter("order");
        String name = req.getParameter("name");


        //各参数的校验
        if (StringUtils.isEmpty(page) || StringUtils.isEmpty(limit)) {
            resp.getWriter().println(JacksonUtil.writeValueAsString(ResponseUtil.badArgument()));
            return;
        }
        //对于sql语句中的sort和order的值,全部默认值
        if (StringUtils.isEmpty(sort)) {
            sort = "add_time";
        }
        if (StringUtils.isEmpty(order)) {
            order = "desc";
        }

        List<MarketLog> result = logService.getLogs(page, limit, sort, order, name);

        resp.getWriter().println(JacksonUtil.writeValueAsString(ResponseUtil.okList(result)));
    }
}

